﻿ #region Disclaimer/Info
 
 /////////////////////////////////////////////////////////////////////////////////////////////////
 //
 //   File:		NhibernateSessionModule.cs
 //   Website:		http://dexterblogengine.com/
 //   Authors:		http://dexterblogengine.com/About.ashx
 //   Rev:		1
 //   Created:		19/01/2011
 //   Last edit:		19/01/2011
 //   License:		GNU Library General Public License (LGPL)
 //   File:            NhibernateSessionModule.cs
 //   For updated news and information please visit http://dexterblogengine.com/
 //   Dexter is hosted to Codeplex at http://dexterblogengine.codeplex.com
 //   For any question contact info@dexterblogengine.com
 //
 ///////////////////////////////////////////////////////////////////////////////////////////////////
 
 #endregion

using System;
using System.Web;
using Dexter.Repository.NHibernate.SessionFactory;

namespace Dexter.Dependency.Castle.NHibernate {


	/// <summary>
	/// The HttpModule used for the lifecycle "PerWebRequest" to optimize the NHibernate.ISession uses.
	/// </summary>
	public class NhibernateSessionModule : IHttpModule {
		ISessionFactory SessionFactory { get; set; }

		#region IHttpModule Members

		/// <summary>
		/// Disposes of the resources (other than memory) used by the module that implements <see cref="T:System.Web.IHttpModule"/>.
		/// </summary>
		public void Dispose ( ) {}


		/// <summary>
		/// Initializes a module and prepares it to handle requests.
		/// </summary>
		/// <param name="context">An <see cref="T:System.Web.HttpApplication"/> that provides access to the methods, properties, and events common to all application objects within an ASP.NET application</param>
		public void Init ( HttpApplication context ) {
			context.Error += ContextError;
			context.EndRequest += ContextEndRequest;
			SessionFactory = DexterContainer.Resolve <ISessionFactory> ( );
		}

		#endregion

		/// <summary>
		/// Contexts the end request.
		/// </summary>
		/// <param name="sender">The sender.</param>
		/// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
		void ContextEndRequest ( object sender , EventArgs e ) {
			SessionFactory.CloseCurrentSession ( true );
		}

		/// <summary>
		/// Contexts the error.
		/// </summary>
		/// <param name="sender">The sender.</param>
		/// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
		void ContextError ( object sender , EventArgs e ) {
			SessionFactory.CloseCurrentSession ( false );
		}
	}
}
